<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="搜索内容" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="分组" prop="group">
        <el-select v-model="queryParams.group" placeholder="分组" clearable style="width: 240px">
          <el-option v-for="item in aiAgentGroupOptions" :key="item.group" :label="item.group" :value="item.group" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="handleInit"
        >
          <svg-icon icon-class="init" />
          初始化</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mainList" @selection-change="handleSelectionChange" tooltip-effect="light custom-tooltip-effect">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" width="55" align="center" prop="id" />
      <el-table-column label="emoji" align="center" prop="emoji" width="80"/>
      <el-table-column label="模型" align="center" prop="v_ai_model_info" :show-overflow-tooltip="true" />
      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="分组" align="center" prop="group" :show-overflow-tooltip="true" />
      <el-table-column label="系统提示" align="center" prop="system_prompt" :show-overflow-tooltip="false" width="80">
        <template slot-scope="scope">
          <el-tooltip placement="top" effect="dark">
<!--            <div slot="content" style="width: 800px;max-height:800px;overflow-y: scroll;" v-html="compiledMarkdown(scope.row.system_prompt)"></div>-->
            <pre slot="content" class="column_tooltip_pre" >{{(scope.row.system_prompt)}}</pre>
            <div style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;width: 80px;">
            {{scope.row.system_prompt}}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="工具智能体" align="center" prop="v_agent_ids_info" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-row v-for="str in scope.row.v_agent_ids_info">
            {{str}}
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="工具" align="center" prop="v_tools_info" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-row v-for="str in scope.row.v_tools_info">
            {{str}}
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dicts.baseEnumEnabledDisabledOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="created_at" width="160" :formatter="formatterTimeYmdHm"/>
      <el-table-column label="更新时间" align="center" prop="updated_at" width="160" :formatter="formatterTimeYmdHm"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleChangeModel(scope.row)"
          >设置模型</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleChangeRelationshipAgent(scope.row)"
          >设置工具智能体</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleInfo(scope.row)"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleCopy(scope.row)"
          >复制</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <AddAIAgentDialog ref="AddAIAgentDialogRef"></AddAIAgentDialog>
    <AIAgentSelectConfigValueDialog ref="AIAgentSelectConfigValueDialogRef" @ok="getList"/>
    <AIAgentSelectAgentsDialog ref="AIAgentSelectAgentsDialogRef"/>
  </div>
</template>

<script>
import { delAIAgent, getAIAgent, initAIAgent, listAIAgent, listAIAgentGroup } from '@/api/ai'
import AddAIAgentDialog from '@/views/ai-agent/add-ai-agent-dialog.vue'
import AIAgentSelectConfigValueDialog from './ai-agent-select-config-value-dialog.vue'
import AIAgentSelectAgentsDialog from './ai-agent-select-agents-dialog.vue'
import MarkdownIt from 'markdown-it'
const md = new MarkdownIt()

export default {
  name: "AIAgentList",
  components:{
    AddAIAgentDialog,
    AIAgentSelectConfigValueDialog,
    AIAgentSelectAgentsDialog,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日志列表数据
      mainList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        group: undefined,
        chat_id: undefined,
        searchValue: undefined,
      },
      // 详情对话框可见性
      detailVisible: false,
      // 当前查看的日志详情数据
      form: {},

      aiAgentGroupOptions: [],
    };
  },
  created() {
    this.getList();
    this.getAIAgentGroup();
  },
  methods: {
    getAIAgentGroup(){
      listAIAgentGroup().then(res=>{
        this.aiAgentGroupOptions=res.data
      })

    },
    /** 查询日志列表 */
    getList() {
      this.loading = true;
      listAIAgent(this.queryParams).then(response => {
        this.mainList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(e => {
        this.mainList = [];
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleAdd({data,title='新增'}={}){
      this.$refs.AddAIAgentDialogRef.show({
        form:this.sksUtils.mergeFromObject({},data,{
          payMode: 1,
          virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,

        }),
        dialogInfo:{
          title: title,
          submitCallbackSuccess:({resData}={})=>{
            this.getList()
          },
        }
      })
    },
    handleCopy(row){

      getAIAgent({id:row.id}).then(res=>{
        console.log(res)
        let data=res.data
        data.id=undefined
        this.$refs.AddAIAgentDialogRef.show({
          extra: {},
          form: this.sksUtils.mergeFromObject({},data,{
            virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,
          }),
          dialogInfo: {
            title: '新增',
            submitCallbackSuccess:({resData}={})=>{
              this.getList()
            },
          },
        })
      })
    },
    handleEdit(row){
      this.$refs.AddAIAgentDialogRef.showByUniqueId({
        uniqueId: row.id,
        dialogInfo: {
          title: '修改',
          submitCallbackSuccess:({resData}={})=>{
            this.getList()
          },
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.modify,
      })
    },
    handleInfo(row){
      this.$refs.AddAIAgentDialogRef.showByUniqueId({
        uniqueId: row.id,
        dialogInfo: {
          title: '查看'
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.none,
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(() => {
        return delAIAgent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    compiledMarkdown(msg){
      return md.render(msg);;
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    handleInit(){
      this.$modal.confirm('是否初始化？').then(() => {
        return initAIAgent();
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("初始化成功");
      }).catch(() => { });
    },
    handleChangeRelationshipAgent(row){
      this.$refs.AIAgentSelectAgentsDialogRef.showByUniqueId({
        uniqueId: row.id,
        dialogInfo: {
          title: '设置工具智能体',
          submitCallbackSuccess:({submitData, ref})=>{
            this.getList()
          }
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.modify,
      })
    },
    handleChangeModel(row){
     this.$refs.AIAgentSelectConfigValueDialogRef.showByUniqueId({
       uniqueId: row.id,
       dialogInfo: {
         title: '设置模型'
       },
       virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.none,
     })
    }
  }
};
</script>

<style >
/* 注：样式注意不要添加scoped，不然会不起效，建议提到公共样式表中 */
.custom-tooltip-effect{
  max-width: 600px;
  line-height: 23px;
}
.column_tooltip_pre{
  width: 1000px;
  max-height:800px;
  overflow-y: scroll;
  white-space: pre-wrap; /*css-3*/
  white-space: -moz-pre-wrap; /*Mozilla,since1999*/
  white-space: -pre-wrap; /*Opera4-6*/
  white-space: -o-pre-wrap; /*Opera7*/
  word-wrap: break-word; /*InternetExplorer5.5+*/
}
</style>
